﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TANKWAR_alpha
{
    public partial class Form1 : Form
    {
        private Game game;
        private bool Bullet_FiredOrplayertank_moved; //unenable playertank to shoot bullets when pressing SpaceKey for quite a time
        
        private Graphics g;
        private Graphics gMap;
        int musicPictureNum = 0;
        
       
        public Form1()
        {
            InitializeComponent();
            //axWindowsMediaPlayer1.GotFocus += ax_getfocus;
            //axWindowsMediaPlayer1.ClickEvent += ax_click;
        }
       

        private void Form1_Load(object sender, EventArgs e)
        {
            //new Thread(new ThreadStart(() => {
            //    Thread.Sleep(100);
            //    this.BeginInvoke(new Action(() => {
            //        this.Invalidate();
            //    }));
            //})).Start();
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer |ControlStyles.UserPaint,true);
            this.UpdateStyles();

            GameGDI gameGDI = new GameGDI();
            Collision collision = new Collision(gameGDI);
            game = new Game(collision);

            g = login.CreateGraphics();
            gMap = Map.CreateGraphics();
           
        }

        //使得在调用pictureBox.Invalidate()时，来触发这个事件，从而重绘控件所在区域

        private void pictureBox1_Paint(object sender, PaintEventArgs e)  
        {
            game.Render(e.Graphics);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            /*
             * there is the most important part, because the run of game depends on these codes
             */
            
            this.Map.Invalidate();   //force pictureBox to repait in order to render

            if (game.GameState == false)
            {
                DateTime now = DateTime.Now;
                while (now.AddSeconds(1) > DateTime.Now) ;

                this.timer1.Enabled = false;
                this.timer2.Enabled = false;
                this.timer3.Enabled = false;

                ClearAllData();    //clear all previous datas
                toolStripProgressBar1.Value = 40;
                toolStripStatusLabel1.Text = "敌方坦克生命值：40";
                this.Map.Invalidate();
                if (game.VictoryOrDie == false)
                    ShowGameOverDie();
                else ShowGameOverWin();
            }
             game.Run();
            
        }

        private void ShowGameOverWin()
        {
            MessageBox.Show("You Win!!!");
            while (login.Left != 0)
            {
                this.Refresh();
                //axWindowsMediaPlayer1.Refresh();
                login.Left += 15;
                Thread.Sleep(10);
            }
        }

        private void ShowGameOverDie()
        {
            MessageBox.Show("You Lose!!!");
            while (login.Left !=0)
            {
                this.Refresh();
                //axWindowsMediaPlayer1.Refresh();
                login.Left += 15;
                Thread.Sleep(10);
            }
        }

        private void ClearAllData()         //when the game ended, clear the data in time
        {
            game.GameEngine.PlayerBullets.Clear();
            game.GameEngine.RobotBullets.Clear();
            game.GameEngine.TankRobots.Clear();
            game.GameEngine.MyTank = null;
            game.GameEngine.RobotBoss = null;
            game.GameEngine.Explodes.Clear();
            game.GameEngine.Walls.Clear();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            /*
             *  the function is to generate RobotTanks automatically, keep their 
             *  number to 4 all the time
             */
            if (game .GameEngine.TankRobots.Count<4)
            {
                int left, top;
                left = game.GameEngine.D.Next(0,25);
                top = game.GameEngine.D.Next(0, 13);
                if(game.Collision.BornInBlankGround(left*Constant.CanvasUnit,top*Constant.CanvasUnit))
                {
                    TankRobot taR = new TankRobot(left * Constant.CanvasUnit, top * Constant.CanvasUnit,game.GameEngine);
                    game.GameEngine.TankRobots.Add(taR);
                    PlayMusic.Play(@"Music\AddRobotTank.wav");
                }
            }
            
        }
       

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            Bullet_FiredOrplayertank_moved = true;
            //MessageBox.Show("Windows Get focus to KeyUp");
            
        }

        /*
         * the following is something about the panel of login, to make the UI more 
         * friendly and more elaborate
         */

        /*
         * the login interface 
         */
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            string title = "欢迎来到坦克世界";
            LinearGradientBrush myBrush = new LinearGradientBrush(ClientRectangle, Color.Red, Color.Yellow, LinearGradientMode.Horizontal);
            g.DrawString(title, new Font("华文隶书", 45, FontStyle.Bold), myBrush, new PointF(10, 49));
            g.DrawImage(game.GameEngine.Imusic_picture[musicPictureNum], 235, 230, 85, 99);
        }

        #region some keys about pictureboxes to changes guanshu or music
        private void ReduceNum_Click(object sender, EventArgs e)
        {
            byte num;
            if ((num = Convert.ToByte(Number.Text)) > 1)
                Number.Text = Convert.ToString(num - 1);
            
        }

        private void AddNum_Click(object sender, EventArgs e)
        {
            byte num;
            if ((num = Convert.ToByte(Number.Text)) < Constant.GuanShu)
                Number.Text = Convert.ToString(num + 1);
        }


        
        private void AddNum_MouseEnter(object sender, EventArgs e)
        {
            //AddNum.BackColor = Color.Yellow;
            (sender as PictureBox).Width = 74;
            (sender as PictureBox).Height = 71;
        }

        private void AddNum_MouseLeave(object sender, EventArgs e)
        {
            (sender as PictureBox).Width = 67;
            (sender as PictureBox).Height = 64;
        }
        
        
        private void MusicR_Click(object sender, EventArgs e)
        {
            musicPictureNum = (++musicPictureNum) % 10;
            login.Refresh();
            g.DrawImage(game.GameEngine.Imusic_picture[musicPictureNum],235,230,85,99);

        }

        private void MusicL_Click(object sender, EventArgs e)
        {
            if (musicPictureNum == 0)
                musicPictureNum = 10;
            musicPictureNum--;
            login.Refresh();
            g.DrawImage(game.GameEngine.Imusic_picture[musicPictureNum], 235, 230, 85, 99);
        }

        #endregion


        /**************Start button function***************/
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            while (login.Left >(-1)* statusStrip1.Width)
            {
                login.Left -= 15;
                this.Refresh();
                Thread.Sleep(10);
            }
            //panel1.Invalidate();

            game.GameState = true;
            game.Prepare(Convert .ToByte(Number.Text));
            Bullet_FiredOrplayertank_moved = true;
            timer1.Enabled = true;
            timer2.Enabled = true;
            timer3.Enabled = true;

            //play music
            axWindowsMediaPlayer1.URL = game.GameEngine.musicPath[musicPictureNum];
            //axWindowsMediaPlayer1.URL = @"Music\秦时明月.mkv";
        }

      
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {

            bool changDir = true;
            //if (Bullet_FiredOrplayertank_moved == true&&game.IsKeyDownToMove==false)
            //{
            if (game.IsKeyDownToMove == false)
                switch (e.KeyCode)
                {
                    case Keys.W: changDir = game.GameEngine.MyTank.MoveByPlayerJudge(MoveDirection.UP); break;
                    case Keys.S: changDir = game.GameEngine.MyTank.MoveByPlayerJudge(MoveDirection.DOWN); break;
                    case Keys.A: changDir = game.GameEngine.MyTank.MoveByPlayerJudge(MoveDirection.LEFT); break;
                    case Keys.D: changDir = game.GameEngine.MyTank.MoveByPlayerJudge(MoveDirection.RIGHT); break;
                    case Keys.H:
                        {
                            changDir = true;
                            if (Bullet_FiredOrplayertank_moved == true)
                            {
                                game.GameEngine.MyTank.ShootByPlayer(); 
                            }
                        }break;
                    default: changDir = true; break;//never happen
                }
            //}
            if (changDir == false)
            {
                game.IsKeyDownToMove = true;
            }

            Bullet_FiredOrplayertank_moved = false;
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            toolStripProgressBar1.PerformStep();
            toolStripStatusLabel1.Text = "敌方坦克生命值："+toolStripProgressBar1.Value.ToString();
            if(toolStripProgressBar1.Value==20)  //should be 40
            {
                timer2.Enabled = false;
                int left, top;
                while(true)
                {
                    left = game.GameEngine.D.Next(0, 25);
                    top = game.GameEngine.D.Next(0, 13);
                    if (game.Collision.BornInBlankGround(left * Constant.CanvasUnit, top * Constant.CanvasUnit))
                    {
                        game.GameEngine.RobotBoss= new TankRobot(left * Constant.CanvasUnit, top * Constant.CanvasUnit, game.GameEngine);
                        game.GameEngine.RobotBoss.Type = 1;
                        game.GameEngine.TankRobots.Add(game.GameEngine.RobotBoss);
                        PlayMusic.Play(@"Music\AddRobotTank.wav");
                        break;
                    }
                }
            }
            //if(toolStripProgressBar1.Value==toolStripProgressBar1.Maximum||(game.GameEngine.TankRobots.Count==0&&game.GameEngine.RobotBoss==null))
            if(toolStripProgressBar1.Value==0||game.GameEngine.TankRobots.Count==0)
            {
                game.GameState = false;
                game.VictoryOrDie=true;
            }
        }

     

       
    }
}
